package cstore

import (
	"fmt"

	"github.com/qiniu/api.v7/kodo"

	"mutu/misc"
	"mutu/misc/conf"
)

var (
	QiNiuAccessKey = conf.GetString("QiNiuAccessKey")
	QiNiuSecretKey = conf.GetString("QiNiuSecretKey")
	QiNiuPubBucket = conf.GetString("QiNiuPubBucket")
	QiNiuPubDomain = conf.GetString("QiNiuPubDomain")
	QiNiuPriBucket = conf.GetString("QiNiuPriBucket")
	QiNiuPriDomain = conf.GetString("QiNiuPriDomain")
)

func init() {

	kodo.SetMac(QiNiuAccessKey, QiNiuSecretKey)
}
func GetDomain(ispub bool) string {
	domain := QiNiuPubDomain
	if !ispub {
		domain = QiNiuPriDomain
	}
	return domain
}

func GetBaseUrl(ispub bool, key string) string {
	domain := GetDomain(ispub)
	base := kodo.MakeBaseUrl(domain, key)

	if ispub {
		return base
	} else {
		zone := 0
		c := kodo.New(zone, nil) // 用默认配置创建 Client
		return c.MakePrivateUrl(base, nil)
	}
}

func GetUploadToken(domain string, ispub bool, uuid string) string {
	bucket := QiNiuPubBucket
	if !ispub {
		bucket = QiNiuPriBucket
	}
	zone := 0                // 您空间(Bucket)所在的区域
	c := kodo.New(zone, nil) // 用默认配置创建 Client
	key := fmt.Sprintf("%s/%d/${fname}", uuid, misc.GTimer.Unix)
	pubstr := "1"
	if !ispub {
		pubstr = "0"
	}
	val := fmt.Sprintf("flag=$(x:flag)&ispub=%s&uuid=%s&bucket=$(bucket)&key=$(key)&fname=$(fname)&imageAve=$(imageAve)&size=$(fsize)&type=$(mimeType)&hash=$(etag)&w=$(imageInfo.width)&h=$(imageInfo.height)",
		pubstr, uuid)
	ul := fmt.Sprintf("http://%s/resource/upload/callback", domain)
	policy := &kodo.PutPolicy{
		Scope:        bucket,
		CallbackUrl:  ul,
		CallbackBody: val,
		Expires:      3600,
		SaveKey:      key,
	}
	token := c.MakeUptoken(policy)
	return token
}
